function _arrayBufferToBase64( buffer ) {
  var binary = '';
  var bytes = new Uint8Array( buffer );
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
      binary += String.fromCharCode( bytes[ i ] );
  }
  return window.btoa( binary );
}

function _downloadB64(b64, name, mime='application/octet-stream') {
  // mime = 'application/vnd.ms-excel'

  _download(`data:${mime};base64,${b64}`, name)
}

function _download(src, name) {
  const a = document.createElement('a');
  a.setAttribute('download', name);
  a.setAttribute('href', src);
  a.setAttribute('target', '_blank');
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

export function downloadFile(url, name) {
  _download(url, name)
}

export function saveFileFromArrayBuffer(bf: ArrayBuffer, name: string) {
  const b64 = _arrayBufferToBase64(bf);
  _downloadB64(b64, name);
}

export function saveFileFromBase64(b64, name, mime?) {
  _downloadB64(b64, name, mime);
}

export function saveFile(src, name) {
  _download(src, name);
}